package cn.hanlyjiang.originwebviewdemo;

import android.app.Activity;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

    protected Button btnJavaCallJS;
    protected Button btnJSCallJava;
    protected LinearLayout topLayout;
    protected WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_main);
        initView();
        initWebView();
    }

    private void initView() {
        btnJavaCallJS = (Button) findViewById(R.id.btnJavaCallJS);
        btnJavaCallJS.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webView.evaluateJavascript("javascript:androidAlert('Android对话框','Android->JS->Android " +
                        "\\n调用Android webView.evaluateJavascript的对话框')",null);
            }
        });
        btnJSCallJava = (Button) findViewById(R.id.btnJSCallJava);
        topLayout = (LinearLayout) findViewById(R.id.topLayout);
        webView = (WebView) findViewById(R.id.webView);
    }

    private void initWebView() {
        webView.getSettings().setJavaScriptEnabled(true);
        // 不影响android对话框弹出 影响 window.open()
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.addJavascriptInterface(new JsObject(this), "Android");
//        webView.loadDataWithBaseURL("file:///android_asset/index.html","","text/html","UTF-8",null);
        webView.loadUrl("file:///android_asset/index.html");
    }

    private static class JsObject {
        private Activity activity;

        public JsObject(Activity activity) {
            this.activity = activity;
        }

        /**
         * @param title
         * @param message
         */
        @JavascriptInterface
        public void alert(String title, String message) {
            new AlertDialog.Builder(activity).setTitle(title)
                    .setMessage(message)
                    .create().show();
        }
    }
}
